package com.iwhalecloud.bss.kite.cucc.service.reception;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.callclient.service.IOrderQueryService;
import com.iwhalecloud.bss.kite.common.entity.InfService;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.api.portal.ILoginService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICuccLoginService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.login.CuccLoginInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.login.auth.CuccAuthLoginInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.UserQueryDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustBusiLicenseDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.LocalCustInfoVO;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalCallClientEnum;
import com.iwhalecloud.bss.kite.cucc.service.attr.LocalAttrHelper;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccContextCustCache;
import com.iwhalecloud.bss.kite.cucc.service.inst.ProdInstService;
import com.iwhalecloud.bss.kite.cucc.service.reception.bo.CustReceptionBO;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 *
 */
@Service("localCustReceptionService")
@Transactional(rollbackFor = Exception.class)
public class CustReceptionService implements ICustReceptionService {
    @Value("${interface.call.mode:hsf}")
    private String mode;

    @Autowired
    private ILoginService loginService;

    @Autowired
    private CustReceptionBO custReceptionBO;

    @Resource
    private IInfServiceBus infServiceBus;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private ProdInstService prodInstService;

    @Autowired
    private ICustReceptionService custReceptionService;
    @Override
    public DataResult<Boolean> ssoLogin(String sessionId) {
        //TODO 先调我们门户的登录服务，后续换为联通登录服务
        loginService.pretendLogin("777100091", "a_123456");

        //custReceptionBO.ssoLogin(sessionId);

        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }

    @Override
    public DataResult<CuccLoginInfoDTO> getLoginInfo(String sessionId) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionId", sessionId);
        String loginInfoJson = HttpsCallClient.getString(CallClientEnum.QRY_LOGIN_INFO, params);

        Map loginInfoMap = JSON.parseObject(loginInfoJson, Map.class);
        if ((Integer) loginInfoMap.get("code") != 0) {
            return ErrorConsts.SUCCESS.getResult(null);
        }
        String loginInfo = (String) loginInfoMap.get("data");
        return ErrorConsts.SUCCESS
            .getResult(JSONObject.toJavaObject(JSON.parseObject(loginInfo), CuccLoginInfoDTO.class));
    }

    @Override
    public DataResult<CuccCustInfoDTO> getCustInfo(String key) {
        return custReceptionBO.getCustInfo(key);
    }

    @Override
    public PageInfo<CuccCustInfoDTO> customerListQuery(KiteCustomerInfoReq kiteCustomerInfoReq) {
        PageInfo<CuccCustInfoDTO> pageInfo = custReceptionService.customerListQueryNew(kiteCustomerInfoReq);
        return pageInfo;
    }

    @Override
    public DataResult<CuccCustInfoDTO> getCustInfoByCustId(String custId) {
        String key = "";
        String staffCode = ContextUtil.getSimpleLoginInfo().getStaffCode();
        String eparchyCode = ContextUtil.getSimpleLoginInfo().getLanId();
        key = staffCode + "_" + custId + "_" + eparchyCode;
        CuccCustInfoDTO cuccCustInfoDTO = this.getCustInfo(key).getResultObject();

        return ErrorConsts.SUCCESS.getResult(cuccCustInfoDTO);
    }

    @Override
    public DataResult<CuccCustInfoDetailDTO> getCustomerDetail(KiteCustomerInfoReq kiteCustomerInfoReq) {
        Map custInfo = new HashMap();
        custInfo.put("provinceCode", kiteCustomerInfoReq.getProvinceCode());
        custInfo.put("eparchyCode", kiteCustomerInfoReq.getEparchyCode());
        custInfo.put("staffCode", kiteCustomerInfoReq.getStaffCode());
        custInfo.put("custId", kiteCustomerInfoReq.getCustId());
        CuccCustInfoDetailDTO cuccCustInfoDTO = new CuccCustInfoDetailDTO();
        Map<String, Object> customerDetailMap = infServiceBus.getCustomerDetail(custInfo);
        if (KiteMapUtils.isNotEmpty(customerDetailMap)) {
            Map<String, Object> customerDetailDataMap = (Map<String, Object>) customerDetailMap.get("data");
            cuccCustInfoDTO = JsonUtils
                .parseObject(KiteMapUtils.getString(customerDetailDataMap, "CUST_INFO"), CuccCustInfoDetailDTO.class);
        }
        return ErrorConsts.SUCCESS.getResult(cuccCustInfoDTO);
    }

    @Override
    public LocalCustInfoVO getCustInfoBySceneInstId(String sceneInstId) {
        Map<String, Object> orderInfoMap = querySceneInstService.getExtParameterValue(sceneInstId, "orderInfoMap");
        if (KiteMapUtils.isEmpty(orderInfoMap)) {
            return null;
        }
        List<KiteAttr> commonAttrList = querySceneInstService.listCommonAttrs(sceneInstId, "30");
        Map<String, Object> custMap = (Map<String, Object>) Optional.ofNullable(orderInfoMap.get("customer")).orElse(Collections.EMPTY_MAP);
        Map<String, Object> linkman = (Map<String, Object>) Optional.ofNullable(orderInfoMap.get("linkman")).orElse(Collections.EMPTY_MAP);
        Map<String, Object> levelAttrs = (Map<String, Object>) Optional.ofNullable(custMap.get("levelAttrs")).orElse(Collections.EMPTY_MAP);
        custMap.putAll(linkman);
        custMap.putAll(levelAttrs);

        commonAttrList.stream().forEach(commonAttr -> {
            commonAttr.setValue(KiteMapUtils.getString(custMap, commonAttr.getFieldName()));
            if (KiteStringUtils.equals(commonAttr.getFieldName(), "location")) {
                commonAttr.setValue(KiteMapUtils.getString(custMap, "eparchyProvinceName") + "-"
                    + KiteMapUtils.getString(custMap, "eparchyCityName") + "-"
                    + KiteMapUtils.getString(custMap, "eparchyAreaName"));
            }
            operateSceneInstService.setCommonAttrValue(sceneInstId, commonAttr.getFieldName(), commonAttr.getValue(), commonAttr.getValue());
        });

        LocalCustInfoVO custDetailVO = new LocalCustInfoVO();
        custDetailVO.setTitle("基本信息");
        custDetailVO.setInfoList(commonAttrList);

        return custDetailVO;
    }

    @Override
    public LocalCustInfoVO getCustomerDetailToChange(Map<String, String> custInfoMap, String sceneInstId) {
        Map<String, Object> customerDetailMap = infServiceBus.getCustomerDetail(custInfoMap);
        List<KiteAttr> commonAttrList = querySceneInstService.listCommonAttrs(sceneInstId, "31");
        if (KiteMapUtils.isNotEmpty(customerDetailMap)) {
            Map<String, Object> customerDetailDataMap = KiteMapUtils.getValue(customerDetailMap, "data");
            Map<String, Object> custInfoResult = KiteMapUtils.getValue(customerDetailDataMap, "CUST_INFO");
            commonAttrList.stream().forEach(commonAttr -> {
                commonAttr.setValue(KiteMapUtils.getString(custInfoResult, commonAttr.getFieldName()));
                operateSceneInstService.setCommonAttrValue(sceneInstId, commonAttr.getFieldName(),
                    commonAttr.getValue(), commonAttr.getValue());
            });
        }
        LocalCustInfoVO custDetailVO = new LocalCustInfoVO();
        custDetailVO.setTitle("基本信息");
        custDetailVO.setInfoList(commonAttrList);
        return custDetailVO;
    }

    @Override
    public CuccAuthLoginInfoDTO pretendLogin(String sessionId) {
        Map<String, Object> result = infServiceBus.qryLoginInfo(sessionId);
        if (!KiteStringUtils.equals(KeyConsts.SUCCESS_0, KiteMapUtils.getString(result, "resultCode"))) {
            BssException.throwOut("41301002", "S-SYS-00027", "登录已超时，请重新登录");
        }
        Map<String, Object> resultObjectMap = KiteMapUtils.getValue(result, "resultObject");
        CuccAuthLoginInfoDTO loginInfo = JSON.parseObject(resultObjectMap.toString(), CuccAuthLoginInfoDTO.class);
        return loginInfo;
    }

    @Override
    public DataResult<Boolean> pretendLoginFromOrder(String sessionId) {
        CuccLoginInfoDTO cuccLoginInfo = this.getLoginInfo(sessionId).getResultObject();
        if (cuccLoginInfo == null) {
            BssException.throwOut("41301002", "S-SYS-00027", "登录已超时，请重新登录");
        }
        ICuccLoginService loginService = SpringUtil.getBean(ICuccLoginService.class);
        loginService.saveLoginInfo(sessionId, cuccLoginInfo);
        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }


    @Override
    public PageInfo<CuccCustInfoDTO> customerListQueryNew(KiteCustomerInfoReq kiteCustomerInfoReq) {



        Map<String, Object> pageReq = new HashMap<>();
        pageReq.put("PAGE_SIZE", kiteCustomerInfoReq.getPageSize());
        pageReq.put("PAGE_NUM", kiteCustomerInfoReq.getPageNum());
//        pageReq.put("CUST_STATES", "0");
        //用户类别（不查个人客户‘0’,小微企业"1"）
//        pageReq.put("CUST_CLASS_TYPE", "2,3,4,5");
        //集团编码
        pageReq.put("GROUP_ID", kiteCustomerInfoReq.getGroupId());
        //省份客户编码
        pageReq.put("PROVINCE_CUST_ID", kiteCustomerInfoReq.getProvinceCustId());
        //cBSS客户编码
        pageReq.put("CUST_ID", kiteCustomerInfoReq.getCustId());
        // 业务号码转成custId
        if (KiteStringUtils.isNotBlank(kiteCustomerInfoReq.getAccNum())) {
            LoginInfo login = ContextUtil.getLoginInfo();
            String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
            String provinceCode = login.getUserInfo().getPostProvinceNbr();
            String eparchyCode = login.getUserInfo().getPostLanId();
            Map<String,Object> userInfoMap = SpringUtil.getBean(ProdInstService.class).queryCustIdByAccNum(kiteCustomerInfoReq.getAccNum(),
                    staffCode, provinceCode, eparchyCode);
             String custId = KiteMapUtils.getString(userInfoMap, "CUST_ID");
            if (KiteStringUtils.isNotBlank(custId) && (KiteStringUtils.isBlank(kiteCustomerInfoReq.getCustId())
                || KiteStringUtils.equals(custId, kiteCustomerInfoReq.getCustId()))) {
                pageReq.put("CUST_ID", custId);
            }
            else {
                return new PageInfo<>(new ArrayList<>());
            }
        }
        //集团客户名称
        pageReq.put("CUST_NAME", kiteCustomerInfoReq.getCustName());
        //省份编码
        pageReq.put("PROVINCE_CODE", kiteCustomerInfoReq.getProvinceCode());

        //证件类型
        pageReq.put("CERT_TYPE_CODE", kiteCustomerInfoReq.getCertTypeCode());
        //证件编码
        pageReq.put("CERT_CODE", kiteCustomerInfoReq.getCertCode());

        //客户状态
        if (KiteStringUtils.isNotEmpty(kiteCustomerInfoReq.getCustStates())){
            pageReq.put("CUST_STATES", kiteCustomerInfoReq.getCustStates());
        }


        Map<String, Object> tcpCont = new HashMap<>();

        Map<String, Object> operUserInfo = new HashMap<>();
        //云联网国际客户列表查询
        String provinceCode=ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(!KiteStringUtils.isEmpty(provinceCode)&&provinceCode.startsWith("48")||provinceCode.startsWith("49")){
            Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();

            operUserInfo.put("USER_CODE", KiteMapUtils.getStrValue(extParams,"account"));
//            pageReq.put("EPARCHY_CODE", "499");
        }else {
            operUserInfo.put("USER_CODE",ContextUtil.getSimpleLoginInfo().getUserCode());
            //地市编码（国际工号不传地市编码）
            pageReq.put("EPARCHY_CODE", kiteCustomerInfoReq.getEparchyCode());
        }

        operUserInfo.put("ROLE_ID", "0");

        pageReq.put("TCP_CONT", tcpCont);
        pageReq.put("OPER_USER_INFO", operUserInfo);

        Map<String, Object> uniBssBodyMap = new HashMap<>();
        uniBssBodyMap.put("PAGE_REQ", pageReq);

        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBodyMap);
        PageHelper.startPage(kiteCustomerInfoReq.getPageNum(), kiteCustomerInfoReq.getPageSize());

        Map<String, Object> restultMap = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_CUSTOMER_LIST.getCenterCode(),LocalCallClientEnum.QRY_CUSTOMER_LIST.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        Map<String, Object> resultBodyMap = KiteMapUtils.getValue(restultMap, "UNI_BSS_BODY");
        Map<String, String> pageRsp = KiteMapUtils.getValue(resultBodyMap, "PAGE_RSP");
        List<CuccCustInfoDTO> cuccCustInfoDTOList = JsonUtils
            .parseArray(KiteMapUtils.getString(pageRsp, "DATA_LIST"), CuccCustInfoDTO.class);
        if (!KiteListUtils.isEmpty(cuccCustInfoDTOList)) {
            cuccCustInfoDTOList.stream().forEach(cuccCustInfoDTO ->{
                String custId = cuccCustInfoDTO.getCustId();
                cuccCustInfoDTO.setCbssId(custId);
                cuccCustInfoDTO.setEparchyName(cuccCustInfoDTO.getProvinceName()+"-"+cuccCustInfoDTO.getEparchyName());

                //客户组织机构代码
                if(KiteStringUtils.equals(cuccCustInfoDTO.getCertiTypeCode(), "S")){
                    cuccCustInfoDTO.setCuccOrgCode(cuccCustInfoDTO.getCertiCode());
                }
            });
            PageInfo<CuccCustInfoDTO> pageInfo = new PageInfo<>(cuccCustInfoDTOList);
            pageInfo.setTotal(KiteMapUtils.getLongValue(pageRsp, "TOTAL_ROW"));
            return pageInfo;
        }
        return new PageInfo<CuccCustInfoDTO>(new ArrayList<>());
    }

    @Override
    public PageInfo<CuccCustInfoDTO> customerListQueryNewForNational(KiteCustomerInfoReq kiteCustomerInfoReq) {

        Map<String, Object> resultMap=this.getCustomerListNewForNational(kiteCustomerInfoReq);

        Map<String, Object> resultBodyMap = KiteMapUtils.getValue(resultMap, "UNI_BSS_BODY");
        Map<String, String> pageRsp = KiteMapUtils.getValue(resultBodyMap, "PAGE_RSP");
        List<CuccCustInfoDTO> cuccCustInfoDTOList = JsonUtils
            .parseArray(KiteMapUtils.getString(pageRsp, "CUST_INTERNATION_DOCUMENT"), CuccCustInfoDTO.class);
        if (!KiteListUtils.isEmpty(cuccCustInfoDTOList)) {
            cuccCustInfoDTOList.stream().forEach(cuccCustInfoDTO ->{
                String custId = cuccCustInfoDTO.getCustId();
                cuccCustInfoDTO.setCbssId(custId);
                cuccCustInfoDTO.setEparchyName(cuccCustInfoDTO.getProvinceName()+"-"+cuccCustInfoDTO.getEparchyName());

                //客户组织机构代码
                if(KiteStringUtils.equals(cuccCustInfoDTO.getCertiTypeCode(), "S")){
                    cuccCustInfoDTO.setCuccOrgCode(cuccCustInfoDTO.getCertiCode());
                }
            });
            PageInfo<CuccCustInfoDTO> pageInfo = new PageInfo<>(cuccCustInfoDTOList);
            pageInfo.setTotal(KiteMapUtils.getLongValue(pageRsp, "TOTAL_ROW"));
            return pageInfo;
        }
        return new PageInfo<CuccCustInfoDTO>(new ArrayList<>());

    }

    //国际客户列表查询(暂时不用)
    private Map<String, Object> getCustomerListNewForNational(KiteCustomerInfoReq kiteCustomerInfoReq) {

        Map<String, Object> dataMap = new HashMap<>();
        IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
        InfService infService = orderQueryService.queryServiceBySvcCode(
            CallClientEnum.QRY_NATIONAL_CUST_LIST.getServiceCode(), CallClientEnum.QRY_NATIONAL_CUST_LIST.getCenterCode());

        if (infService == null) {
            ErrorConsts.SERVICE_UNREGISTERED.throwOut(
                CallClientEnum.QRY_NATIONAL_CUST_LIST.getCenterCode() + ":" + CallClientEnum.QRY_NATIONAL_CUST_LIST
                    .getServiceCode());
        }
        Map<String, Object> uniBssBody = new HashMap<>();
        Map<String, Object> custInternationalDocument = new HashMap<>();
        Map<String, Object> tcpCount=new HashMap<>();
        tcpCount.put("APP_KEY","");
        tcpCount.put("TRANSACION_ID","");

        custInternationalDocument.put("TCP_CONT",tcpCount);
        Map<String, Object> operUserInfo = new HashMap<>();
        operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());
        operUserInfo.put("STAFF_ID",ContextUtil.getSimpleLoginInfo().getStaffId());

        custInternationalDocument.put("OPER_USER_INFO",operUserInfo);

        //cBSS客户编码
        custInternationalDocument.put("CUST_ID", kiteCustomerInfoReq.getCustId());
        // 业务号码转成custId
        if (KiteStringUtils.isNotBlank(kiteCustomerInfoReq.getAccNum())) {
            LoginInfo login = ContextUtil.getLoginInfo();
            String staffCode = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
            String provinceCode = login.getUserInfo().getPostProvinceNbr();
            String eparchyCode = login.getUserInfo().getPostLanId();
            Map<String,Object> userInfoMap = SpringUtil.getBean(ProdInstService.class).queryCustIdByAccNum(kiteCustomerInfoReq.getAccNum(),
                staffCode, provinceCode, eparchyCode);
            String custId = KiteMapUtils.getString(userInfoMap, "CUST_ID");
            if (KiteStringUtils.isNotBlank(custId) && (KiteStringUtils.isBlank(kiteCustomerInfoReq.getCustId())
                || KiteStringUtils.equals(custId, kiteCustomerInfoReq.getCustId()))) {
                custInternationalDocument.put("CUST_ID", custId);
            }
            else {
                return null;
            }
        }
        custInternationalDocument.put("GROUP_ID", kiteCustomerInfoReq.getGroupId());
        custInternationalDocument.put("SEARCH_LOGIN_NO", "");
        custInternationalDocument.put("CUST_INDUSTRY", "");
        //客户类型
        custInternationalDocument.put("SIGN_FLAG", "");
        custInternationalDocument.put("PAGE_SIZE",kiteCustomerInfoReq.getPageSize());
        custInternationalDocument.put("PAGE_NO",kiteCustomerInfoReq.getPageNum());
        custInternationalDocument.put("ENG_NAME", "");
        custInternationalDocument.put("CONTACT_POSITION", "");
        custInternationalDocument.put("AUDIT_STATUS", "");
        custInternationalDocument.put("CHN_NAME", "");
        //所属专业线
        custInternationalDocument.put("TYPE_CODE", "");
        //客户状态
        custInternationalDocument.put("STATUS_CODE", "");
        custInternationalDocument.put("PROVINCE_CODE", kiteCustomerInfoReq.getProvinceCode());
        custInternationalDocument.put("EPARCHY_CODE", kiteCustomerInfoReq.getEparchyCode());
        custInternationalDocument.put("GROUP_CUST_FLAG", "");
        custInternationalDocument.put("DEPT_ID", "");
        custInternationalDocument.put("SALE_MANAGER_LIST", "");
        custInternationalDocument.put("REGION_AREA_CODE", "");
        custInternationalDocument.put("SALE_MANAGER", "");

        uniBssBody.put("CUST_INTERNATION_DOCUMENT_REQ",custInternationalDocument);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBody);
        param.put("OP_CODE","json_chinaUnicom_govEnterprise_customerCenter_custInternationDocument");
        InfServiceHelper.adaptGray(param, custInternationalDocument);
        String resultStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            resultStr = HttpsCallClient.postStringWithObject(CallClientEnum.QRY_NATIONAL_CUST_LIST, param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            resultStr = infExchangeService.exchange(new JSONObject(param));
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(CallClientEnum.QRY_NATIONAL_CUST_LIST.getServiceCode(), "获取国际客户列表信息",
                "获取国际客户列表信息失败");
        }
        Map result = JSON.parseObject(resultStr, Map.class);
        Map uniBssHead = (Map) result.get("UNI_BSS_HEAD");
        if (KiteMapUtils.isNotEmpty(uniBssHead)) {
            String respDesc = KiteMapUtils.getString(uniBssHead, "RESP_DESC");
            if (KiteStringUtils.isEqual("Success", respDesc)) {
                Map bodyMap = (Map) result.get("UNI_BSS_BODY");
                Map requestRsp = (Map) bodyMap.get("CUST_INTERNATION_DOCUMENT_RSP");
                dataMap = (Map<String, Object>) requestRsp.get("data");
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取国际客户列表信息", "获取国际客户列表信息失败");
            }
        }else{
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(CallClientEnum.QRY_WORKORDER_INFO.getServiceCode(), "获取国际客户列表信息", "获取国际客户列表信息失败");
        }
        return dataMap;


    }

    @Override
    public CuccCustInfoDetailDTO getCustomerInfoNew(String custId) {

        Map tcpCont = new HashMap();
        tcpCont.put("APP_KEY", "kite");
        tcpCont.put("TRANSACION_ID", RandomStringUtils.randomNumeric(18));

        Map operUserInfo = new HashMap();
        operUserInfo.put("STAFF_ID", "");
        operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());

        Map qryCustinfoDetailReq = new HashMap();
        qryCustinfoDetailReq.put("TCP_CONT", tcpCont);
        qryCustinfoDetailReq.put("OPER_USER_INFO", operUserInfo);
        CuccContextCustDTO custDto = CuccContextCustCache.get(ContextUtil.getLoginInfo().getUserInfo().getUserCode(), custId);
        if (Objects.nonNull(custDto) && KiteStringUtils.isNotEmpty(custDto.getCbssId())
            && KiteStringUtils.isEqual(custDto.getCustId(), custId)) {
            custId = custDto.getCbssId();
        }
        if(KiteStringUtils.isEmpty(custId)){
            custId = custDto.getCbssId();
        }
        qryCustinfoDetailReq.put("CUST_ID", custId);

        Map uniBssBodyMap = new HashMap();

        uniBssBodyMap.put("QRY_CUSTINFO_DETAIL_REQ", qryCustinfoDetailReq);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBodyMap);

        Map customerDetailMap = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_CUSTOMER_DETAIL.getCenterCode(),LocalCallClientEnum.QRY_CUSTOMER_DETAIL.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        Map<String, Object> customerDetailDataMap = KiteMapUtils.getMap(customerDetailMap, "UNI_BSS_BODY");
        Map<String, String> custinfoDetailRsp = (Map<String, String>) customerDetailDataMap.get("QRY_CUSTINFO_DETAIL_RSP");
        if (custinfoDetailRsp == null) {
        	ErrorConsts.INF_INVOKE_ERROR
            .throwOut(LocalCallClientEnum.QRY_CUSTOMER_DETAIL.getServiceCode(), "查询客户详情失败", "");
        }
        CuccCustInfoDetailDTO cuccCustInfoDTO = JsonUtils
            .parseObject(KiteMapUtils.getString(custinfoDetailRsp, "CUST_INFO"), CuccCustInfoDetailDTO.class);
        if (cuccCustInfoDTO == null) {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_CUSTOMER_DETAIL.getServiceCode(), "查询客户详情失败", "");
        }
        String provinceCode = LocalAttrHelper.getRegionName(cuccCustInfoDTO.getProvinceCode());
        String eparchyCode = LocalAttrHelper.getRegionName(cuccCustInfoDTO.getEparchyCode());
        provinceCode = KiteStringUtils.join(provinceCode, Symbols.HYPHEN, eparchyCode);
        cuccCustInfoDTO.setEparchyName(provinceCode);

        //客户营业执照
        CuccCustBusiLicenseDTO cuccCustBusiLicenseDTO = JsonUtils
            .parseObject(KiteMapUtils.getString(custinfoDetailRsp, "CUST_BUSI_LICENSE"), CuccCustBusiLicenseDTO.class);
        if (Objects.nonNull(cuccCustBusiLicenseDTO)){
            cuccCustInfoDTO.setCustBusiLicense(cuccCustBusiLicenseDTO);
        }
        // 客户联系人邮箱
        if (custinfoDetailRsp.containsKey("CUST_TRANSACTOR")) {
            Map<String, Object> custTransactor = KiteMapUtils.getMap(custinfoDetailRsp, "CUST_TRANSACTOR");
            cuccCustInfoDTO.setContactEmail(KiteMapUtils.getString(custTransactor, "EMAIL"));
        }
        return cuccCustInfoDTO;
    }

    @Override
    public CuccCustInfoDetailDTO getCustomerInfoNewForNational(String custId) {

        Map<String, Object> resultMap=this.getCustomerDetailForNational(custId);
        Map<String, Object> customerDetailDataMap = KiteMapUtils.getMap(resultMap, "UNI_BSS_BODY");
        Map<String, String> custinfoDetailRsp = KiteMapUtils.getValue(customerDetailDataMap,"QRY_INTERNATIONAL_CUST_INFO_RSP");
        if (custinfoDetailRsp == null) {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_INTERNATIONALCUSTOMER_DETAIL.getServiceCode(), "查询国际客户详情失败", "");
        }
        List<CuccCustInfoDetailDTO> cuccCustInfoDetailDTOS=JsonUtils.parseArray(KiteMapUtils.getString(custinfoDetailRsp, "DATA_LIST"),CuccCustInfoDetailDTO.class);
        CuccCustInfoDetailDTO cuccCustInfoDTO = cuccCustInfoDetailDTOS.get(0);
        if (cuccCustInfoDTO == null) {
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.QRY_INTERNATIONALCUSTOMER_DETAIL.getServiceCode(), "查询国际客户详情失败", "");
        }
        String provinceCode = LocalAttrHelper.getRegionName(cuccCustInfoDTO.getProvinceCode());
        String eparchyCode = LocalAttrHelper.getRegionName(cuccCustInfoDTO.getEparchyCode());
        provinceCode = KiteStringUtils.join(provinceCode, Symbols.HYPHEN, eparchyCode);
        cuccCustInfoDTO.setEparchyName(provinceCode);

//        //客户营业执照
//        CuccCustBusiLicenseDTO cuccCustBusiLicenseDTO = JsonUtils
//            .parseObject(KiteMapUtils.getString(custinfoDetailRsp, "CUST_BUSI_LICENSE"), CuccCustBusiLicenseDTO.class);
//        if (Objects.nonNull(cuccCustBusiLicenseDTO)){
//            cuccCustInfoDTO.setCustBusiLicense(cuccCustBusiLicenseDTO);
//        }
//        // 客户联系人邮箱
//        if (custinfoDetailRsp.containsKey("CUST_TRANSACTOR")) {
//            Map<String, Object> custTransactor = KiteMapUtils.getMap(custinfoDetailRsp, "CUST_TRANSACTOR");
//            cuccCustInfoDTO.setContactEmail(KiteMapUtils.getString(custTransactor, "EMAIL"));
//        }
        return cuccCustInfoDTO;
    }

    private Map<String, Object> getCustomerDetailForNational(String custId) {
        Map<String, Object> dataMap = new HashMap<>();

        Map tcpCont = new HashMap();
        tcpCont.put("APP_KEY", "kite");
        tcpCont.put("TRANSACION_ID", RandomStringUtils.randomNumeric(18));

        Map operUserInfo = new HashMap();
        operUserInfo.put("STAFF_ID", "");

        //云联网国际客户详情查询
        String provinceCode=ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if(!KiteStringUtils.isEmpty(provinceCode)&&provinceCode.startsWith("48")||provinceCode.startsWith("49")){
            Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();

            operUserInfo.put("USER_CODE", KiteMapUtils.getStrValue(extParams,"account"));
        }else {
            operUserInfo.put("USER_CODE",ContextUtil.getSimpleLoginInfo().getUserCode());
        }

        Map qryInternationalDetail = new HashMap();
        qryInternationalDetail.put("TCP_CONT", tcpCont);
        qryInternationalDetail.put("OPER_USER_INFO", operUserInfo);
        //分页
        qryInternationalDetail.put("PAGE_SIZE",Integer.valueOf(10));
        qryInternationalDetail.put("PAGE_NUM",Integer.valueOf(1));
        qryInternationalDetail.put("PROVINCE_CODE",provinceCode);

        CuccContextCustDTO custDto = CuccContextCustCache.get(ContextUtil.getLoginInfo().getUserInfo().getUserCode(), custId);
        if (Objects.nonNull(custDto) && KiteStringUtils.isNotEmpty(custDto.getCbssId())
            && KiteStringUtils.isEqual(custDto.getCustId(), custId)) {
            custId = custDto.getCbssId();
        }
        if(KiteStringUtils.isEmpty(custId)){
            custId = custDto.getCbssId();
        }
        qryInternationalDetail.put("CUST_ID", custId);

        Map uniBssBodyMap = new HashMap();

        uniBssBodyMap.put("QRY_INTERNATIONAL_CUST_INFO_REQ",qryInternationalDetail);
        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBodyMap);
        param.put("OP_CODE","json_jike_natureCustCenter_qryInternationalCustInfo");
        InfServiceHelper.adaptGray(param, qryInternationalDetail);
        String resultStr;
        if (KiteStringUtils.isEqual(mode, "http")) {
            resultStr = HttpsCallClient.postStringWithObject(LocalCallClientEnum.INF_COMMON_URL, param, LocalTokenUtil.getHeaderMap());
        }
        else {
            InfExchangeService infExchangeService = SpringUtil.getBean("infExchangeService");
            resultStr = infExchangeService.exchange(new JSONObject(param));
        }
        if (KiteStringUtils.isEmpty(resultStr)) {
            ErrorConsts.INF_INVOKE_ERROR.throwOut(LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), "获取国际客户详情信息",
                "获取国际客户详情信息失败");
        }
        Map result = JSON.parseObject(resultStr, Map.class);
        Map uniBssHead = (Map) result.get("UNI_BSS_HEAD");
        if (KiteMapUtils.isNotEmpty(uniBssHead)) {
            String respDesc = KiteMapUtils.getString(uniBssHead, "RESP_CODE");
            if (KiteStringUtils.isEqual("00000", respDesc)) {
               dataMap=result;
            }
            else {
                ErrorConsts.INF_INVOKE_ERROR
                    .throwOut(LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), "获取国际客户详情信息", "获取国际客户详情信息失败");
            }
        }else{
            ErrorConsts.INF_INVOKE_ERROR
                .throwOut(LocalCallClientEnum.INF_COMMON_URL.getServiceCode(), "获取国际客户详情信息", "获取国际客户详情信息失败");
        }
        return dataMap;



    }

    @Override
    public PageInfo<CuccCustInfoDTO> queryCustomerTransferList(KiteCustomerInfoReq kiteCustomerInfoReq) {
        Map<String, Object> pageReq = new HashMap<>();
        pageReq.put("PAGE_SIZE", kiteCustomerInfoReq.getPageSize());
        pageReq.put("PAGE_NUM", kiteCustomerInfoReq.getPageNum());
        //用户类别（不查个人客户‘0’,小微企业"1"） 客户不包括小微客户、目标客户（未录入完整的客户）
        pageReq.put("CUST_CLASS_TYPE", "0,2,3,4,5");
        //集团编码
        pageReq.put("GROUP_ID", kiteCustomerInfoReq.getGroupId());
        //省份客户编码
        pageReq.put("PROVINCE_CUST_ID", kiteCustomerInfoReq.getProvinceCustId());
        //cBSS客户编码
        pageReq.put("CUST_ID", kiteCustomerInfoReq.getCustId());
        //集团客户名称
        pageReq.put("CUST_NAME", kiteCustomerInfoReq.getCustName());
        //省份编码
        pageReq.put("PROVINCE_CODE", kiteCustomerInfoReq.getProvinceCode());
        //地市编码
        pageReq.put("EPARCHY_CODE", kiteCustomerInfoReq.getEparchyCode());
        //证件类型
        pageReq.put("CERT_TYPE_CODE", kiteCustomerInfoReq.getCertTypeCode());
        //证件编码
        pageReq.put("CERT_CODE", kiteCustomerInfoReq.getCertCode());
        //客户状态
        if (KiteStringUtils.isNotEmpty(kiteCustomerInfoReq.getCustStates())) {
            pageReq.put("CUST_STATES", kiteCustomerInfoReq.getCustStates());
        }

        Map<String, Object> tcpCont = new HashMap<>();

        Map<String, Object> operUserInfo = new HashMap<>();
        operUserInfo.put("USER_CODE", ContextUtil.getSimpleLoginInfo().getUserCode());
        operUserInfo.put("ROLE_ID", "0");

        pageReq.put("TCP_CONT", tcpCont);
        pageReq.put("OPER_USER_INFO", operUserInfo);

        Map<String, Object> uniBssBodyMap = new HashMap<>();
        uniBssBodyMap.put("PAGE_REQ", pageReq);

        Map<String, Object> param = LocalTokenUtil.getParamMap(uniBssBodyMap);
        PageHelper.startPage(kiteCustomerInfoReq.getPageNum(), kiteCustomerInfoReq.getPageSize());

        Map<String, Object> restultMap = HttpsCallClient.postObjMap(LocalCallClientEnum.QRY_CUSTOMER_LIST.getCenterCode(), LocalCallClientEnum.QRY_CUSTOMER_LIST.getServiceCode(), param, LocalTokenUtil.getHeaderMap());
        Map<String, Object> resultBodyMap = KiteMapUtils.getValue(restultMap, "UNI_BSS_BODY");
        Map<String, String> pageRsp = KiteMapUtils.getValue(resultBodyMap, "PAGE_RSP");
        List<CuccCustInfoDTO> cuccCustInfoDTOList = JsonUtils
            .parseArray(KiteMapUtils.getString(pageRsp, "DATA_LIST"), CuccCustInfoDTO.class);
        if (!KiteListUtils.isEmpty(cuccCustInfoDTOList)) {
            cuccCustInfoDTOList.stream().filter(cuccCustInfoDTO -> !KiteStringUtils.equals("1", cuccCustInfoDTO.getExamineSts())).collect(Collectors.toList());
            cuccCustInfoDTOList.stream().forEach(cuccCustInfoDTO -> {
                String custId = cuccCustInfoDTO.getCustId();
                cuccCustInfoDTO.setCbssId(custId);
                cuccCustInfoDTO.setEparchyName(cuccCustInfoDTO.getProvinceName() + "-" + cuccCustInfoDTO.getEparchyName());

                //客户组织机构代码
                if (KiteStringUtils.equals(cuccCustInfoDTO.getCertiTypeCode(), "S")) {
                    cuccCustInfoDTO.setCuccOrgCode(cuccCustInfoDTO.getCertiCode());
                }
            });
            PageInfo<CuccCustInfoDTO> pageInfo = new PageInfo<>(cuccCustInfoDTOList);
            pageInfo.setTotal(KiteMapUtils.getLongValue(pageRsp, "TOTAL_ROW"));
            return pageInfo;
        }
        return new PageInfo<CuccCustInfoDTO>(new ArrayList<>());
    }

    @Override
    public PageInfo<CuccCustInfoDTO> customerListQueryNewCloud(KiteCustomerInfoReq kiteCustomerInfoReq) {
        PageInfo<CuccCustInfoDTO> customerListPage = this.customerListQueryNew(kiteCustomerInfoReq);
        List<CuccCustInfoDTO> customerLists = customerListPage.getList();
        Iterator<CuccCustInfoDTO> iterator = customerLists.iterator();
        while (iterator.hasNext()) {
            CuccCustInfoDTO customerList = iterator.next();
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("custId", String.valueOf(customerList.getCustId()));
            paramMap.put("provinceCode", customerList.getProvinceCode());
            paramMap.put("eparchyCode", customerList.getEparchyCode());
            paramMap.put("pageNum", "1");
            paramMap.put("pageSize", "10");
            UserQueryDTO userQueryDTO = prodInstService.listCloudProdInst(paramMap);
            if (KiteListUtils.isEmpty(userQueryDTO.getUserList().getList())) {
                iterator.remove();
            }
            return customerListPage;
        }
        return new PageInfo<CuccCustInfoDTO>(new ArrayList<>());
    }
}
